<template>
<!--面包屑-->
<div style="margin-bottom: 30px;">
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <router-link to="/MenuModule/MenuDisplay">菜单管理</router-link>
    </el-breadcrumb-item>
    <el-breadcrumb-item>新增菜单</el-breadcrumb-item>
  </el-breadcrumb>
</div>

  <el-form ref="ruleFormRef" style="max-width: 600px;margin: auto;" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="菜单权限" prop="parent_id">
       <el-select v-model="form.parent_id" placeholder="请选择菜单权限">
        <el-option label="顶级菜单" :value="0"></el-option>
         <el-option v-for="item in menuSelectData" :key="item.id" :label="item.menu_name" :value="item.id"></el-option>
       </el-select>
    </el-form-item>

    <el-form-item label="菜单名称" prop="menu_name">
      <el-input v-model="form.menu_name" placeholder="请输入菜单名称" />
    </el-form-item>
    
    <el-form-item label="菜单Url" prop="menu_url">
      <el-input v-model="form.menu_url" placeholder="请输入菜单Url" />
    </el-form-item>

    <el-form-item label="授权" prop="perms">
      <el-input v-model="form.perms" placeholder="请输入授权" />
    </el-form-item>

    <el-form-item label="类型" prop="type">
      <el-select v-model="form.type" placeholder="请选择类型">
        <el-option label="目录" :value="0" />
        <el-option label="菜单" :value="1" />
      </el-select>
    </el-form-item>

    <el-form-item label="菜单图标" prop="menu_icon">
      <el-input v-model="form.menu_icon" placeholder="请输入菜单图标" />
    </el-form-item>

    <el-form-item label="排序" prop="order_num">
      <el-input v-model="form.order_num" placeholder="请输入排序" />
    </el-form-item>

    <el-form-item label="按钮" prop="permsButton">
      <el-switch v-model="form.permsButton" />
    </el-form-item>

  <el-form v-if="form.permsButton==true" :model="form" ref="formRef">
    <div v-for="(form, index) in form.button" :key="index">
      <el-form-item :prop="'button.' + index + '.permission_name'" label="功能名称">
        <el-input v-model="form.permission_name" placeholder="请输入功能名称" style="width: 180px;" ></el-input>
      </el-form-item>
      <el-form-item :prop="'button.' + index + '.is_perms'" label="功能路径">
        <el-input v-model="form.is_perms" placeholder="请输入功能路径" style="width: 180px;" ></el-input>
        <el-button type="danger" @click="removeButton(index)">删除行</el-button>
      </el-form-item>
    </div>
    <el-button type="primary" @click="addButton">新增行</el-button>
  </el-form>

        <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import {useRoute,useRouter} from 'vue-router'

//图片上传
import { Plus } from '@element-plus/icons-vue'
const handleAvatarSuccess = (val:any) => {
    form.driverLicenseImg = val
}

const route = useRoute();
const router = useRouter();
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const formRef:any = ref(null);
  
const props = {
  checkStrictly: true,
  expandTrigger: 'hover' as const,
}


onMounted(() => {
  getPermission()

  getMenuSelect()
})

//form表单
const form: any = reactive({
  parent_id: "",
  menu_name	: "",
  menu_url: "",
  perms	: "",
  type: "",
  menu_icon: "",
  order_num: '',
  radioButton: '',
  permission_name: '',
  is_perms:'',
  button: [
        { permission_name:'', is_perms: '' } // 初始权限对象
  ],
})

const buttonArray=ref([])


//校验
const rules = reactive<FormRules>({
  parent_id: [
    { required: true, message: '请输入菜单父级id', trigger: 'blur' },
  ],
  menu_name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  menu_url: [
    { required: true, message: '请输入菜单Url', trigger: 'blur' },
  ],
  // perms: [
  //   { required: true, message: '请输入授权', trigger: 'blur' },
  // ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  // menu_icon: [
  //   { required: true, message: '请输入菜单图标', trigger: 'blur' },
  // ],
  order_num:  [
    { required: true, message: '请输入排序', trigger: 'blur' },
  ],
})

//菜单select
const menuSelectData:any=ref([])
const getMenuSelect = () => {
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuSelectShow').then(res=>{
    console.log(res);
    menuSelectData.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}

//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let roleAdd = {
        parent_id: form.parent_id,
        menu_name	: form.menu_name,
        menu_url: form.menu_url,
        perms	: form.perms,
        type: form.type,
        menu_icon: form.menu_icon,
        order_num: form.order_num,
        // 使用map来遍历button数组并构造每个对象
        button: form.button.map((btn:any, index:any) => ({
          permission_name: btn.permission_name,
          is_perms: btn.is_perms
        }))
      }
      axios.post('http://1.117.93.87:8000/rbacxie/api/Menu/menuCreate',roleAdd,).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage.success("创建成功!")
          router.push('/MenuModule/AddCharacterMenu')
        } else if (res.data.code == 2001) {
          ElMessage.error("菜单已存在")
          
          return
        } else {
          ElMessage.error("创建失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//角色权限树形
const RolePermissionData:any=ref([])

const getPermission=()=>{
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuTreeShow').then(res=>{
    console.log(res);
    RolePermissionData.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}

interface DomainItem {
  key: number
  value: string
}

const addButton = () => {
      form.button.push({ permission_name: '', is_perms: '' });
      // 调用更新验证规则的方法（但请注意上面的注意事项）
      // updateRules(); // 由于响应式限制，这里注释掉
    };
 
    const removeButton = (index:any) => {
      form.button.splice(index, 1);
      // 移除对应的验证规则（同样需要手动更新，但在这个示例中我们忽略了这一步）
      // 由于响应式限制，这里不直接操作 rules 对象
    };

//----------------------------------
//新增行
const addInput = () => {
  form.dynamicForm.counter.push({'permission_name': '', 'is_perms': ''})
}

//删除行
const delInput = (index:any) => {
  form.dynamicForm.counter.splice(index, 1)
}

</script>

<style scoped>

</style>